/*
# Copyright (c) 2020-2030 iSoftStone Information Technology (Group) Co.,Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
*/
import PreviewPresenter from '../../presenter/PreviewPresenter.js';
import seetaface from '@ohos.napi_seetaface';
import file from '@system.file'
import featureAbility from '@ohos.ability.featureAbility';

const PERMISSIONS = ["ohos.permission.MEDIA_LOCATION",
"ohos.permission.READ_MEDIA",
"ohos.permission.WRITE_MEDIA",
"ohos.permission.CAMERA",
"ohos.permission.MICROPHONE"]

const IS_DEBUG = true
const LOCAL_FACE_ROOT = '/data/accounts/account_0/appdata/com.example.facedetect/files/'
const LOCAL_FACE_PATH = 'internal://app/files'
let mPreviewPresenter
let interval = 0
let self

export default {
    data: {
        previewAreaWidth: 0,
        previewAreaHeight: 0,
        footerHeight: 0,
        footerWrapMargin: 0,
        resultColor: 0x0000,
        isDetecting: false,
        isDetectSuccess: false,
        faceStatusImg: '/common/media/weijc.png',
        faceResult: '请检测后通过',
        timeText: '00:00',
        dateText: '2022-03-18',
        loadImages: []
    },
    onInit() {
        self = this
        reqPermissions().then(() => {
            mPreviewPresenter = new PreviewPresenter(this.$app.$def.data.previewModel)
            mPreviewPresenter.getAppStyle((data) => {
                log('getAppStyle data -- ' + JSON.stringify(data))
                this.previewAreaWidth = data.previewWidth
                this.previewAreaHeight = data.previewHeight
                this.footerHeight = data.footerHeight
                this.footerWrapMargin = data.footerWrapMargin
            })
            self.updateTime()
        }).catch(() => {
            log('reqPermissions -- fail -- ')
        })
    },
    onShow() {
        self.faceResult = '正在初始化'
        getLoadImages().then((data) => {
            self.loadImages = data
        })
        self.isDetecting = true
//        clearLocationData().then(() => {
//            log('clearLocationData ... ')
//            setTimeout(() => {
//                self.registerFaceId()
//            }, 1000)
//        })
    },
    registerFaceId() {
        registerFaceId().then(() => {
            setTimeout(() => {
                self.isDetecting = false
                self.faceStatusImg = '/common/media/weijc.png'
                self.faceResult = '请检测后通过'
                self.startDetect()
            }, 2000)
        }).catch(() => {
            log('registerFaceId -- fail -- ')
            self.isDetecting = false
            self.faceResult = '初始化失败'
            self.faceStatusImg = '/common/media/weitg.png'
        })
    },
    startDetect() {
        let callback = (err) => {
            if (err && err == -4) {
                self.startFace(self.$element('CameraId'), callback, 3000)
                return
            }
            if (err) {
                self.faceStatusImg = '/common/media/weitg.png'
                self.faceResult = getErrorMsg(err)
            } else {
                self.updateTime()
                self.faceStatusImg = '/common/media/tongguo.png'
                self.faceResult = '检测通过'
            }
            setTimeout(() => {
                self.faceStatusImg = '/common/media/weijc.png'
                self.faceResult = '请检测后通过'
                self.startFace(self.$element('CameraId'), callback, 0)
            }, 3000)
        }
        self.startFace(self.$element('CameraId'), callback, 3000)
    },
    startFace(element, callback, time) {
        let camera = element
        let call = callback
        setTimeout(() => {
            takePhoto(camera).then((object) => {
                log(`takePhoto success `)
                call(object)
            }).catch((code) => {
                log('takePhoto fail  ... ' + code)
                call(code)
            })
        }, time)
    },
    updateTime() {
        clearInterval(interval)
        interval = setInterval(() => {
            let date = new Date()
            self.timeText = formatTime(date)
            self.dateText = formatDate(date)
        }, 10000)
    }
}

function reqPermissions() {
    return new Promise((resolve, reject) => {
        featureAbility.getContext().requestPermissionsFromUser(PERMISSIONS, 0, (result) => {
            if (result) {
                log('requestPermissionsFromUser result -- ' + JSON.stringify(result))
                let authResults = result.authResults
                let sum = 0
                for (let i = 0; i < authResults.length; i++) {
                    sum += authResults[i]
                }
                log('data sum: ' + sum)
                if (sum >= -1) {
                    resolve()
                } else {
                    reject()
                }
            }
        })
    })
}

var formatTime = function (date) {
    let hours = date.getHours()
    let minutes = date.getMinutes()
    return `${fill(hours)}:${fill(minutes)}`
}

var formatDate = function (date) {
    var yyyy = date.getFullYear()
    var mm = date.getMonth() + 1
    var dd = date.getDate()
    return `${fill(yyyy)}-${fill(mm)}-${fill(dd)}`
}

function fill(value) {
    return (value > 9 ? "" : "0") + value
}

function drawHeader(ctx, disWidth) {
    ctx.ellipse(110 - 63, 221, 40, 10, Math.PI * -0.08, Math.PI * 1.06, Math.PI * 1.78, 0);
    ctx.ellipse(110 - 41, 202, 6, 15, Math.PI * 0, Math.PI * 0.06, Math.PI * 1.82, 1);
    ctx.ellipse(110 - 46, 171, 3, 25, Math.PI * -0.13, Math.PI * 0.5, Math.PI * 1.5, 0);
    ctx.ellipse(110 - 60, 136, 3, 12, Math.PI * -0.10, Math.PI * -1.52, Math.PI * -2.44, 0);
    ctx.arc(110, 100 - 5, 70, Math.PI * 0.9, Math.PI * 1.5);
    ctx.arc(110, 100 - 5, 70, Math.PI * 1.5, Math.PI * 2.1);
    ctx.ellipse(110 + 60, 136, 3, 12, Math.PI * 0.10, Math.PI * 1.52, Math.PI * 2.44, 0);
    ctx.ellipse(110 + 46, 171, 3, 25, Math.PI * 0.13, Math.PI * 1.5, Math.PI * 0.5, 0);
    ctx.ellipse(110 + 41, 202, 6, 15, Math.PI * 0, Math.PI * 1.18, Math.PI * 0.94, 1);
    ctx.ellipse(110 + 63, 221, 40, 10, Math.PI * 0.08, Math.PI * 1.22, Math.PI * 1.94, 0);
    ctx.stroke();
}

async function clearLocationData() {
    return new Promise((resolve, reject) => {
        seetaface.ClearFaceDatabase()
        resolve()
    })
}

async function registerFaceId() {
    return new Promise((resolve, reject) => {
        log('registerFaceId -- ')
        file.list({
            uri: LOCAL_FACE_PATH,
            success: function (data) {
                var fileList = data.fileList
                log('registerFaceId -- fileList --' + fileList)
                var length = fileList.length
                log('registerFaceId -- ' + 'length -- ' + length)
                if (length == 0) {
                    reject()
                    return
                }
                for (var i = 0; i < length; i++) {
                    var fileUri = fileList[i].uri
                    log('registerFaceId -- ' + 'fileUri -- ' + fileUri)
                    var fileName = fileUri.substr(fileUri.lastIndexOf('/'))
                    log('registerFaceId -- ' + 'fileName -- ' + fileName)
                    var imgPath = LOCAL_FACE_ROOT + fileName
                    var last = imgPath.substr(imgPath.lastIndexOf(".")).toLowerCase()
                    log('registerFaceId -- ' + 'last -- ' + last)
                    if (last == '.jpg' || last == '.png') {
                        var id = seetaface.RegisterImage(imgPath)
                        log('registerFaceId -- ' + 'RegisterImage -- ' + id)
                    }
                }
                resolve()
            },
            fail: function (data, code) {
                log('registerFaceId -- fail -- ' + 'code -- ' + code)
                reject()
            }
        })
    })
}

function takePhoto(element) {
    log('takePhoto -- element -- ' + element)
    return new Promise((resolve, reject) => {
        element.takePhoto({
            quality: 'high',
            success: (res) => {
                log('LABEL 9527 takePhoto success -- ' + JSON.stringify(res))
                resolve(undefined)
            },
            fail: (err) => {
                log('LABEL 9527 takePhoto fail -- ' + JSON.stringify(err))
                reject(parseInt(err.errorcode))
            }
        })
    })
}

async function getLoadImages() {
    return new Promise((resolve, reject) => {
        let count = 25
        let images = []
        for (var i = 0; i < count; i++) {
            images.push({
                src: '/common/loading/loading_000' + (i > 9 ? i : '0' + i) + '.png'
            })
        }
        resolve(images)
    })
}

function getErrorMsg(result) {
    var msg
    if (result > 0) {
        if ((result & 1) == 1) {
            msg = '灯光不合格'
            return msg
        }
        if ((result & 2) == 2) {
            msg = '人脸太小'
            return msg
        }
        if ((result & 4) == 4) {
            msg = '人脸姿态不正常'
            return msg
        }
        if ((result & 8) == 8) {
            msg = '清晰度不够'
            return msg
        }
    } else {
        switch (result) {
            case -1:
                msg = '检测未通过'
                break
            case -2:
                msg = '服务处理异常'
                break
            case -3:
                msg = '打开图片出错'
                break
            case -4:
                msg = '未识别出人脸区域'
                break
            case -5:
                msg = '参数类型或者数量有误'
                break
            case -6:
                msg = '人脸数量超出限制'
                break
            case -7:
                msg = '人脸区域不合规'
                break
            default:
                msg = '未知错误'
                break
        }
    }
    return msg
}

function log(msg) {
    if (IS_DEBUG) {
        console.log('FaceDetect - ' + msg)
    }
}